<template>
  <div class="stepWrap">
    <div
      v-for="(c, index) in defaults"
      :key="index"
      class="step"
      :class="{ beforeStep: index !== 0 }"
      :ref="
        (el) => {
          if (el) navItems[index] = el;
        }
      "
    >
      <span
        :class="{ activeSpan: active - 1 > index || index == active - 1 }"
        >{{ index + 1 }}</span
      >
      <div
        class="component"
        :class="{ activeComponent: active - 1 > index || index == active - 1 }"
      >
        <component :is="c" />
      </div>
      <span class="description">{{ c.props.description }}</span>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, watchEffect, watch } from "vue";
import Step from "./StepLib.vue";

export default defineComponent({
  props: { active: { type: Number, default: 0 } },
  setup(props, context) {
    const navItems = ref<HTMLDivElement[]>([]);
    const divs = navItems.value;
    onMounted(() => {
      const div1Right = divs[0].getBoundingClientRect().right;
      const div2left = divs[1].getBoundingClientRect().left;
      const distance = div2left - div1Right + "px";
      styeFun(distance);
    });
    const defaults = context.slots.default?.();
    defaults?.map((component) => {
      if (component.type !== Step) {
        throw new Error("请使用正确的子标签");
      }
    });
    watch(
      () => props.active,
      () => {
        styeFun();
      }
    );
    const styeFun = (distance?: string) => {
      divs.map((div, index) => {
        if (distance)
          index === 0 ? "" : divs[index].style.setProperty("--width", distance);
        if (props.active < 2) {
          divs[index].style.setProperty("--border", "grey");
        } else if (props.active > index) {
          divs[index].style.setProperty("--border", "#68c33c");
        } else {
          divs[index].style.setProperty("--border", "grey");
        }
      });
    };
    return { defaults, navItems };
  },
});
</script>
<style scoped lang="scss">
$color: #68c33c;
.stepWrap {
  display: flex;
  justify-content: space-around;
  .step {
    position: relative;
    padding: 0 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    span {
      display: block;
      text-align: center;
      max-width: 150px;
    }
    .component {
      text-align: center;
    }
    .activeComponent {
      color: $color;
    }
    .description {
      position: absolute;
      min-width: 150px;
      max-width: 200px;
      right: 50%;
      top: 100%;
      transform: translateX(50%);
      margin-top: 10px;
    }
    :first-child {
      border: 2px solid black;
      border-radius: 50%;
      width: 20px;
      line-height: 20px;
    }
    .activeSpan {
      color: $color;
      border: 2px solid $color;
    }
  }
  .beforeStep::before {
    content: "";
    position: absolute;
    top: 50%;
    right: 100%;
    width: var(--width);
    border: 2px solid var(--border);
  }
}
</style>
